/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package map.file;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import map.CachedMap;


import figures.FigureIterator;
import file.FileGetter;
import geometry.Rectangle;

public class CachedIndexMap implements CachedMap{
	
	protected FileGetter g = null;
	protected String n = null;
	protected Rectangle myArea = null;
	protected CombinationMap mm = null;
	
	public CachedIndexMap(FileGetter getter,String name, Rectangle b){
		g = getter;
		n = name;
		myArea = b;
	}
	
	public FigureIterator getFigures(Rectangle area){
		if(myArea!=null && !myArea.colides(area)){
			if(mm!=null)
				unload();
			return null;
		}	
		if(mm==null)
			load();
		return mm.getFigures(area);
	}
	
	public void load(){
		mm =new CombinationMap();
		mm.setArea(myArea);
		try {
			InputStream st = g.getResource(n);
			DataInputStream is = new DataInputStream(st);
			is.readShort();
			while(true)
			{
				byte tipo = is.readByte();
				String str = FileMap.readString(is);
				Rectangle b = new Rectangle();
				b.load(is);
				switch(tipo){
					case FileConstants.FILE_TYPE_MAP:
						mm.appendMap(new CachedFileMap(g, str, b));
						break;
					case FileConstants.FILE_TYPE_INDEX:
						mm.appendMap(new CachedIndexMap(g, str, b));
						break;						
				}
			}
		} catch (EOFException e) {
			//eof
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void unload() {
		mm = null;
		System.gc();
	}

}

	
